package com.practice.J2E.Test;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.collection.CollUtil;

/**
 * @author kayn
 * @create 2023-09-13 下午 02:41
 */
public class IOTest {

    public static void main(String[] args) throws Exception {

        Date date = new Date();

        Thread.sleep(2000);

        Date date1 = new Date();

        System.out.println(DateUtil.betweenMs(date1,date));

//        testFile();

//        testFileCopy();
    }

    private static void testFileCopy() throws Exception{

        File sourceFile = new File("C:\\Users\\1\\Desktop\\test\\txt.txt");

        File targetFile = new File("C:\\Users\\1\\Desktop\\test\\txt2.txt");

        copy(sourceFile,targetFile);
    }

    private static void copy(File sourceFile, File targetFile) throws Exception{

        FileReader reader = new FileReader(sourceFile);

        FileWriter writer = new FileWriter(targetFile);

        char[] buffer = new char[1024];

        int bytesRead;

        while ( (bytesRead = reader.read(buffer)) != -1) {

            writer.write(buffer, 0 ,bytesRead);

        }

        reader.close();

        writer.close();

    }

    /**
     * 测试文件的基本功能
     */
    private static void testFile() {

        File rootFile = new File("C:\\Users\\1\\Desktop\\test");

        List<File> fileList = getAllFile(rootFile,file->StrUtil.endWith(file.getName(),"xlsx"));

        fileList.stream().peek(file -> System.out.println(file.getName())).collect(Collectors.toList());

        System.out.println(rootFile.getAbsolutePath());

        System.out.println(rootFile.getAbsoluteFile());

        System.out.println(rootFile.getPath());

        System.out.println(rootFile.getName());

        System.out.println(rootFile.length());

    }

    /**
     * 遍历子目录及其子目录下符合条件的文件或文件夹
     * @param rootFile
     * @param fileFilter
     * @return
     */
    private static List<File> getAllFile(File rootFile, FileFilter fileFilter) {

        List<File> fileList = CollUtil.newArrayList(rootFile.listFiles())

                .stream()

                .flatMap(file -> getAllFile(file,fileFilter).stream())

                .collect(Collectors.toList());

        if (fileFilter.accept(rootFile)) {

            fileList.add(rootFile);

        }

        return fileList;
    }

}
